/*
Copyright 2022 The Vitess Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package graphviz

import (
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"strings"
)

type (
	Graph struct {
		lastID int
		nodes  []*Node
		edges  []*Edge
	}
	Node struct {
		id      int
		Name    string
		attrs   []string
		tooltip string
	}
	Edge struct {
		From, To *Node
	}
)

func escape(s string) string {
	s = strings.ReplaceAll(s, "<", "\\<")
	s = strings.ReplaceAll(s, ">", "\\>")
	s = strings.ReplaceAll(s, "\"", "\\\"")
	s = strings.ReplaceAll(s, "|", "\\|")
	s = strings.ReplaceAll(s, "{", "\\{")
	s = strings.ReplaceAll(s, "}", "\\}")
	return s
}

func (n *Node) AddAttribute(s string) {
	n.attrs = append(n.attrs, escape(s))
}
func (n *Node) AddTooltip(s string) {
	n.tooltip = escape(s)
}

func (g *Graph) produceDot() string {
	var dot strings.Builder
	dot.WriteString(`digraph {
node [shape=record, fontsize=10]
`)
	for _, node := range g.nodes {
		labels := node.Name
		for i, attr := range node.attrs {
			if i == 0 {
				labels += "|{" + attr
			} else {
				labels += "|" + attr
			}

		}
		labels += "}"
		if node.tooltip != "" {
			dot.WriteString(fmt.Sprintf(`n%d [label="%s", tooltip="%s"]`, node.id, labels, node.tooltip))
		} else {
			dot.WriteString(fmt.Sprintf(`n%d [label="%s"]`, node.id, labels))
		}
		dot.WriteString(";\n")
	}
	for _, edge := range g.edges {
		dot.WriteString(fmt.Sprintf(`n%d -> n%d`, edge.From.id, edge.To.id))
		dot.WriteString(";\n")
	}
	dot.WriteString("}")
	return dot.String()
}

func (g *Graph) AddNode(name string) *Node {
	n := &Node{
		id:   g.lastID,
		Name: name,
	}
	g.lastID++
	g.nodes = append(g.nodes, n)
	return n
}

func (g *Graph) AddEdge(from, to *Node) *Edge {
	e := &Edge{
		From: from,
		To:   to,
	}
	g.edges = append(g.edges, e)
	return e
}

const htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>GraphViz Viewer</title>
    <script src="https://cdn.jsdelivr.net/npm/@hpcc-js/wasm/dist/index.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom/dist/svg-pan-zoom.min.js"></script>
    <script>
        var hpccWasm = window["@hpcc-js/wasm"];
    </script>
	<style>
		#graph svg {
			width: 90vw;
			height: 90vh;
			border-width: 1px;
			border-style: dotted;
		}
	</style>
</head>
<body>
    <div id="graph"></div>
    <script>
		const dot = %s;
        hpccWasm.graphviz.layout(dot, "svg", "dot").then(svg => {
            const div = document.getElementById("graph");
            div.innerHTML = svg;
			svgPanZoom(div.querySelector('svg'), { controlIconsEnabled: true });
        });
    </script>
</body>
</html>
`

func (g *Graph) Render() error {

	dot := g.produceDot()

	browsers := func() []string {
		var cmds []string
		if userBrowser := os.Getenv("BROWSER"); userBrowser != "" {
			cmds = append(cmds, userBrowser)
		}
		switch runtime.GOOS {
		case "darwin":
			cmds = append(cmds, "/usr/bin/open")
		case "windows":
			cmds = append(cmds, "cmd /c start")
		default:
			// Commands opening browsers are prioritized over xdg-open, so browser()
			// command can be used on linux to open the .svg file generated by the -web
			// command (the .svg file includes embedded javascript so is best viewed in
			// a browser).
			cmds = append(cmds, []string{"chrome", "google-chrome", "chromium", "firefox", "sensible-browser"}...)
			if os.Getenv("DISPLAY") != "" {
				// xdg-open is only for use in a desktop environment.
				cmds = append(cmds, "xdg-open")
			}
		}
		return cmds
	}

	tmpfile, err := os.CreateTemp("", "graphviz_*.html")
	if err != nil {
		return err
	}

	_, err = fmt.Fprintf(tmpfile, htmlTemplate, strconv.Quote(dot))
	if err != nil {
		return err
	}
	err = tmpfile.Close()
	if err != nil {
		return err
	}

	for _, b := range browsers() {
		args := strings.Split(b, " ")
		if len(args) == 0 {
			continue
		}
		viewer := exec.Command(args[0], append(args[1:], tmpfile.Name())...)
		viewer.Stderr = os.Stderr
		if err := viewer.Start(); err == nil {
			return nil
		}
	}

	return fmt.Errorf("failed to open browser for SVG debugging")
}

func New() *Graph {
	return &Graph{}
}
